const url = 'http://www.xiongmaoyouxuan.com/';

const data = {
    loading: false,
    isEnd: false,
    pageSize: 20,
    store: {
        banner: [],
        items: []
    },
    record: {},
    // 初始化
    init: function (callback) {
        this.pageSize = 20;
        $.ajax({
            url: url + 'api/tab/1',
            type: 'GET',
            data: {
                start: 0
            },
            dataType: 'JSON',
            success: function (res) {
                if (res.code === 200 && res.data) {
                    this.bannerInit(res.data.banners)
                    this.itemsInit(res.data.items)
                    callback(this.store)
                }
            }.bind(this)
        })
    },
    // banner参数初始化
    bannerInit: function (data) {
        const banner = this.store.banner;
        data.forEach(function (el, i) {
            banner.push(el.imageUrl)
        });
    },
    // 列表参数初始化
    itemsInit: function (data) {
        this.store.items = this.formatItems(data);
    },
    // 格式化items参数
    formatItems: function (data) {
        let arr = [];
        data.list.forEach(function (el, i) {
            if (el.title) {
                const itemsObj = {
                    title: el.title,
                    hasCoupon: el.hasCoupon,
                    couponValue: el.couponValue,
                    isFreePostage: el.isFreePostage,
                    saleNum: el.saleNum >= 10000 ? (el.saleNum / 1000).toFixed(1) + '万' : el.saleNum,
                    priceStrong: el.price.toString().split('.')[0],
                    priceDigit: el.price.toString().split('.')[1],
                    image: el.image,
                    type: el.type === 1 ? '天猫' : '淘宝',
                    typeClass: el.type === 1 ? 'tmall' : 'taobao',
                }
                arr.push(itemsObj)
            }
        })
        return arr
    },
    // 获取新的下拉列表数据
    getNewItems: function (callback) {
        if (this.isEnd || this.record.pageSize == this.pageSize || this.loading) return;
        const load = document.getElementById('load');
        this.loading = true
        load.classList.add('loading');
        $.ajax({
            url: url + 'api/tab/1/feeds',
            type: 'GET',
            dataType: 'JSON',
            data: {
                start: this.pageSize,
                sort: 0
            },
            success: function (res) {
                load.classList.remove('loading');
                this.loading = false
                if (res.data.isEnd) {
                    this.isEnd = true;
                    return
                }
                if (res.code === 200 && res.data) {
                    this.record.pageSize = this.pageSize
                    this.pageSize += 20;
                    callback(this.formatItems(res.data))
                }
            }.bind(this)
        })
    },

}

const index = {
    scorllLock: true,
    lastTop: 0,
    init: function (data) {
        document.getElementById('main').style.display = 'block';
        $('#tab-nav').html('')
        const self = index;
        const moveBtn = document.querySelector('.btn-move');
        self.bannerRender(data, self.swiperInit.bind(this))
        self.itemsRender(data.items)
        moveBtn.addEventListener('click', self.moveItemsRender.bind(this), false);
        window.addEventListener('scroll', function () {
            if (this.scorllLock) return
            const html = document.documentElement;
            const scrollTop = html.scrollTop;
            const scrollHeight = html.scrollHeight;
            const innerHeight = window.innerHeight;
            if (scrollTop + innerHeight >= scrollHeight - 4) {
                // 获取数据并且渲染完毕 fetchDataAndRender
                this.moveItemsRender()
            }
        }.bind(this), false)
    },
    bannerRender: function (data, callback) {
        const bannerData = data.banner;
        const fragment = new DocumentFragment();
        const wrapper = document.getElementById('wrapper')
        bannerData.forEach(function (el, i) {
            const div = document.createElement('div')
            div.className = 'swiper-slide';
            const img = document.createElement('img');
            img.src = el;
            div.append(img)
            fragment.append(div)
        })
        wrapper.append(fragment);
        callback()
    },
    swiperInit: function () {
        if (this.mySwiper) return;
        this.mySwiper = new Swiper('.swiper-container', {
            direction: 'horizontal', // 垂直切换选项
            loop: true, // 循环模式选项

            // 如果需要分页器
            pagination: {
                el: '.swiper-pagination',
                clickable: true,
            },

            // 如果需要前进后退按钮
            navigation: {
                nextEl: '.swiper-button-next',
                prevEl: '.swiper-button-prev',
            },
            // 自动播放
            autoplay: true
        })
    },
    itemsRender: function (data = []) {
        const main = document.querySelector('.choice-list');
        const html = [];
        data.forEach(function (el, i) {
            let itemsHtml = template('items', el)
            html.push(itemsHtml)
        })
        main.insertAdjacentHTML('beforeend', html.join(''));
        // main.innerHTML += html.join('');
    },
    moveItemsRender: function (callback) {
        console.log(this)
        data.getNewItems(function (data) {
            index.itemsRender(data);
            index.scorllLock = false;
            document.querySelector('.btn-move').style.display = 'none';
            typeof callback == 'function' && callback()
        })

    },
    tabChange: function (column, callback) {
        document.getElementById('main').style.display = 'none';
        document.querySelector('.choice-list').innerHTML = '';
        $.ajax({
            type: 'GET',
            url: url + 'api/column/' + column,
            dataType: 'JSON',
            success: function (res) {
                if (res.code === 200 && res.data) {
                    this.subColumn(res)
                }
            }.bind(this)
        })
    },
    subColumn: function (res) {
        const tab = document.querySelector('#tab-nav')
        tab.innerHTML = '';
        const title = res.data.name;
        const tabList = {
            arr: res.data.subColumns.map(function (el, i) {
                return el.name
            })
        };
        const div = document.createElement('div');
        div.className = 'banner-title'
        div.innerHTML = title;
        tab.append(div)
        const html = template('tabList', tabList)
        tab.insertAdjacentHTML('beforeend', html);
        $('.tab-item').eq(0).addClass('active')
    }

}

const route = {
    init: function () {
        this.hashChange()
        this.path[this.hash]()
    },
    hash: 'index',
    hashChange: function () {
        let self = this
        window.addEventListener('hashchange', function () {
            self.hash = location.hash.substr(1);
            if (self.hash === '') {
                self.hash = 'index'
            }
            self.path[self.hash]()
        }, false)
    },
    path: {
        'index': function () {
            data.init(index.init.bind(index))
        },
        'exemption': function () {
            index.tabChange(29, index.itemsRender)
        },
        'coupon': function () {
            index.tabChange(170, index.itemsRender)
        },
        'women': function () {
            index.tabChange(3183, index.itemsRender)
        }
    }
}

$('.nav-list').on('click', '.list-item', function () {
    location.hash = $(this).attr('data-hash')
    $('.list-item').removeClass('active')
    $(this).addClass('active');
})

// backTop

$(window).scroll(function () {
    if ($(this).scrollTop() > 200) {
        $('#back_top').show()
    } else {
        $('#back_top').hide()
    }
})

$('#back_top').on('click', function () {
    console.log(1)
    $('body,html').animate({
        scrollTop: 0
    }, 1000)
})
route.init()


const block = {
    activeTab: 'tab1',
    data: {
        tab1: {
            loadWay: 'loadmore',// init loadmore
            loading: false,
            finish: false,
            api: '',
            data: [],
            pageSize: 1
        },
        tab2: {
            
            loadWay: 'loadmore',// init loadmore
            loading: false,
            finish: false,
            api: '',
            data: [],
            pageSize: 1,
            tabs: {

            }
        },
        tab3: {
            loadWay: 'loadmore',// init loadmore
            loading: false,
            finish: false,
            api: '',
            data: [],
            pageSize: 1
        },
        tab4: {
            loadWay: 'loadmore',// init loadmore
            loading: false,
            finish: false,
            api: '',
            data: [],
            pageSize: 1
        },
    },
    init: function() {
        $('.btn-more').click(function() {
            this.loadMore(function() {
                this.renderItems();
            });
            
        }.bind(this))
    },
    getActiveTab: function() {
        return this.data[this.activeTab]
    },
    fetchData: function(callback) {
        const active = this.getActiveTab()
        if (active.loading) return;
        const load = document.getElementById('load');
        this.loading = true
        load.classList.add('loading');
        // 如果 时拉去数据，就ajax,不是的话 就直接 return data
        if(active.loadWay == 'init') {
            return callback(this.formatItems(active.data))
        }

        $.ajax({
            url: url + active.api,
            type: 'GET',
            dataType: 'JSON',
            data: {
                start: active.pageSize,
                sort: 0
            },
            success: function (res) {
                load.classList.remove('loading');
                this.loading = false
                if (res.data.isEnd) {
                    active.finish = true;
                    return
                }
                if (res.code === 200 && res.data) {
                    active.pageSize += 20;
                    active.data = active.data.cancat(res.data)
                    callback(this.formatItems(res.data))
                }
            }.bind(this)
        })
    },
    renderItems: function() {
        const active = this.getActiveTab()
    },
    loadMore: function(callback) {
        const active = this.getActiveTab()
        active.loadWay = 'loadmore';
        this.fetchData(callback);
    }

}      


$('ul li').click(function() {
    block.getActiveTab().loadWay = 'init';
    block.init();
})